import 'package:chathouse/pages/route_manager/root_route_manager.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/log.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

import '../../../constant/app_constant.dart';
import '../../../model/email_notice_setting_model.dart';
import '../../../model/member_info.dart';
import '../../../model/response_bean.dart';
import '../../../util/base_utils.dart';

/// @class : ContactUsPage
/// @date : 2023-03-09 15:21
/// @name : LFC
/// @description : 电邮及通知设定
class EmailNoticeSettingPage extends StatefulWidget {
  int type; //1 用戶 2專家
  EmailNoticeSettingPage(this.type, {Key? key}) : super(key: key);

  @override
  State<EmailNoticeSettingPage> createState() => _EmailNoticeSettingPageState();
}

class _EmailNoticeSettingPageState extends State<EmailNoticeSettingPage>
    with NavigationHelper {
  var emailSetting = ["新的報價", "報價狀態更新", "專家留言"];
  var noticeSetting = ["所有推送通知", "新的報價", "報價狀態更新", "專家留言", "系統通知"];
  var msgSetting = ["所有推送通知", "報價狀態更新", "預約成功"];

  var emailSettingSwitchState = [false, false, false];
  var noticeSettingSwitchState = [false, false, false, false, false];
  var msgSettingSwitchState = [false, false, false];

  EmailNoticeSettingModel? model;

  @override
  void initState() {
    super.initState();
    Obj.showLoading();
    Apis.getMemberSettingInfo().then((value) {
      Obj.dismissLoading();
      model = EmailNoticeSettingModel.fromJson(value?.data);
      if (model?.code == 200) {
        setState(() {
          emailSettingSwitchState[0] =
              model?.data?.emailNewQuote == "1" ? true : false;
          emailSettingSwitchState[1] =
              model?.data?.emailQuoteSts == "1" ? true : false;
          emailSettingSwitchState[2] =
              model?.data?.emailExpert == "1" ? true : false;

          noticeSettingSwitchState[0] =
              model?.data?.informAll == "1" ? true : false;
          noticeSettingSwitchState[1] =
              model?.data?.informNewQuote == "1" ? true : false;
          noticeSettingSwitchState[2] =
              model?.data?.informQuoteSts == "1" ? true : false;
          noticeSettingSwitchState[3] =
              model?.data?.informExpert == "1" ? true : false;
          noticeSettingSwitchState[4] =
              model?.data?.informSystem == "1" ? true : false;

          msgSettingSwitchState[0] = model?.data?.smsAll == "1" ? true : false;
          msgSettingSwitchState[1] =
              model?.data?.smsQuoteSts == "1" ? true : false;
          msgSettingSwitchState[2] =
              model?.data?.smsAppointment == "1" ? true : false;
        });
      }
    }).catchError((error) {
      Obj.dismissLoading();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
          backgroundColor: Colors.white,
          shadowColor: Colors.transparent,
          leading: Icon(
            Icons.arrow_back_ios,
            size: 18.w,
            color: MyColors.gary_149149149,
          ).setOnClickListener(() {
            back();
          }),
          centerTitle: true,
          title: Text(
            "電郵通知設定",
            textAlign: TextAlign.center,
            style: getTextStyle(30.sp,
                color: Colors.black, fontType: FontType.MID),
          )),
      body: CustomScrollView(
        slivers: [
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.only(bottom: 12.w),
              width: double.infinity,
              height: 0.5.w,
              color: MyColors.gary_199199199,
            ),
          ),
          SliverToBoxAdapter(
            child: Row(
              children: [
                ImageUtils.image(Res.icon_person, width: 22.w, height: 24.w),
                SizedBox(
                  width: 10.w,
                ),
                Text(
                  "用戶電郵設定",
                  style: getTextStyle(22.sp,
                      color: Colors.black, fontType: FontType.MID),
                ),
              ],
            ).setContainer(margin: EdgeInsets.only(left: 20.w)),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate((content, index) {
              return Column(
                children: [
                  Row(
                    children: [
                      Text(
                        emailSetting[index],
                        style: getTextStyle(18.sp,
                            color: Colors.black, fontType: FontType.MID),
                      ),
                      const Spacer(),
                      CupertinoSwitch(
                        activeColor: Colors.pink,
                        dragStartBehavior: DragStartBehavior.down,
                        value: emailSettingSwitchState[index],
                        onChanged: (bool value) {
                          setState(() {
                            emailSettingSwitchState[index] = value;
                            updateMemberSettingInfo(
                                emailSettingSwitchState, index);
                          });
                        },
                      ),
                    ],
                  ).setContainer(
                    margin:
                        EdgeInsets.symmetric(vertical: 10.w, horizontal: 20.w),
                  ),
                  Container(
                    width: double.infinity,
                    height: index == emailSetting.length - 1 ? 20.w : 0.5.w,
                    color: MyColors.gary_210210210,
                  ),
                ],
              );
            }, childCount: emailSetting.length),
          ),
          SliverToBoxAdapter(
            child: Row(
              children: [
                ImageUtils.image(Res.icon_notice, width: 22.w, height: 26.w),
                SizedBox(
                  width: 10.w,
                ),
                Text(
                  "通知設定",
                  style: getTextStyle(22.sp,
                      color: Colors.black, fontType: FontType.MID),
                ),
              ],
            ).setContainer(margin: EdgeInsets.only(left: 20.w, top: 12.w)),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate((content, index) {
              return Column(
                children: [
                  Row(
                    children: [
                      Text(
                        noticeSetting[index],
                        style: getTextStyle(18.sp,
                            color: Colors.black, fontType: FontType.MID),
                      ),
                      const Spacer(),
                      CupertinoSwitch(
                        activeColor: Colors.pink,
                        dragStartBehavior: DragStartBehavior.down,
                        value: noticeSettingSwitchState[index],
                        onChanged: (bool value) {
                          setState(() {
                            noticeSettingSwitchState[index] = value;
                            updateMemberSettingInfo(
                                noticeSettingSwitchState, index);
                          });
                        },
                      ),
                    ],
                  ).setContainer(
                    margin: EdgeInsets.symmetric(
                      vertical: 10.w,
                      horizontal: 20.w,
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    height: index == noticeSetting.length - 1 ? 20.w : 0.5.w,
                    color: MyColors.gary_210210210,
                  ),
                ],
              );
            }, childCount: noticeSetting.length),
          ),
          SliverToBoxAdapter(
            child: Row(
              children: [
                ImageUtils.image(Res.icon_msg, width: 22.w, height: 24.w),
                SizedBox(
                  width: 10.w,
                ),
                Text(
                  "短訊設定",
                  style: getTextStyle(22.sp,
                      color: Colors.black, fontType: FontType.MID),
                ),
              ],
            ).setContainer(margin: EdgeInsets.only(left: 20.w, top: 12.w)),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate((content, index) {
              return Column(
                children: [
                  Row(
                    children: [
                      Text(
                        msgSetting[index],
                        style: getTextStyle(18.sp,
                            color: Colors.black, fontType: FontType.MID),
                      ),
                      const Spacer(),
                      CupertinoSwitch(
                        activeColor: Colors.pink,
                        dragStartBehavior: DragStartBehavior.down,
                        value: msgSettingSwitchState[index],
                        onChanged: (bool value) {
                          setState(() {
                            msgSettingSwitchState[index] = value;
                            updateMemberSettingInfo(
                                msgSettingSwitchState, index);
                          });
                        },
                      ),
                    ],
                  ).setContainer(
                    margin:
                        EdgeInsets.symmetric(vertical: 10.w, horizontal: 20.w),
                  ),
                  Container(
                    width: double.infinity,
                    height: index == msgSetting.length - 1 ? 0.w : 0.5.w,
                    color: MyColors.gary_199199199,
                  ),
                ],
              );
            }, childCount: msgSetting.length),
          ),
          SliverToBoxAdapter(
            child: Container(
              height: 40.w,
            ),
          )
        ],
      ),
    );
  }

  void updateMemberSettingInfo(List stateList, int index) async {
    Apis.getMembersInfo().then((value) {
      var jsonData = value?.data;
      var _memberInfo = MemberInfo.fromJson(jsonData);
      SpUtil.putObject(AppConstant.memberInfo, _memberInfo!);

      Obj.showLoading();
      final params = {
        "emailNewQuote": emailSettingSwitchState[0] == true ? "1" : "0",
        "emailQuoteSts": emailSettingSwitchState[1] == true ? "1" : "0",
        "emailExpert": emailSettingSwitchState[2] == true ? "1" : "0",
        "informAll": noticeSettingSwitchState[0] == true ? "1" : "0",
        "informNewQuote": noticeSettingSwitchState[1] == true ? "1" : "0",
        "informQuoteSts": noticeSettingSwitchState[2] == true ? "1" : "0",
        "informExpert": noticeSettingSwitchState[3] == true ? "1" : "0",
        "informSystem": noticeSettingSwitchState[4] == true ? "1" : "0",
        "smsAll": msgSettingSwitchState[0] == true ? "1" : "0",
        "smsQuoteSts": msgSettingSwitchState[1] == true ? "1" : "0",
        "smsAppointment": msgSettingSwitchState[2] == true ? "1" : "0",
        "membersId": _memberInfo.data?.membersId,
        "membersNo": _memberInfo.data?.membersNo,
        "membersName": _memberInfo.data?.membersName,
        "version": model?.data?.version,
        "settingsId": model?.data?.settingsId
      };
      Apis.updateMemberSettingInfo(params).then((value) {
        Obj.dismissLoading();
        var result = ResponseBean.fromJson(value?.data ?? {});
        LogUtil.d("contact success $value");
        if (!result.isRequestSuccess) {
          stateList[index] = !stateList[index];
          setState(() {});
        } else {
          // ToastUtil.showToast(result.msg);
        }
      }).catchError((error) {
        Obj.dismissLoading();
        stateList[index] = !stateList[index];
        setState(() {});
      });
    }).catchError((error) {
      Obj.dismissLoading();
      LogUtil.d("getMembersInfo error");
    });

  }
}
